package com.recordhistory.controller;

import cn.hutool.core.io.file.FileReader;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recordhistory.enums.ResultEnum;
import com.recordhistory.exception.ServiceException;
import com.recordhistory.model.*;
import com.recordhistory.model.vo.ReignTitleVo;
import com.recordhistory.service.*;
import com.recordhistory.utils.CheckTool;
import com.recordhistory.utils.CommonTool;
import com.recordhistory.utils.NumberConventerTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：LX
 * 创建时间： 2019/6/13. 15:51
 * 地点：广州
 * 目的: 其他 附加的
 * 备注说明：
 */
@Controller
@RequestMapping("/other")
public class AdditionalController {

    @Autowired
    private PeriodService periodService;
    @Autowired
    private ReignTitleService reignTitleService;
    @Autowired
    private LandService landService;
    @Autowired
    private HistoryImgService historyImgService;
    @Autowired
    private HistoryMainService historyMainService;


    /**
     * 跳转到 新增时期
     * @return
     */
    @RequestMapping("/toAddPeriod")
    public String toAddPeriod(ModelMap modelMap){
        List<HistoryMain> historyMainList = historyMainService.selectAllAdSort();
        modelMap.put("historyMainList", historyMainList);

        return "addPeriod";
    }

    /**
     * 新增 时期
     * @param period 时期data
     */
    @RequestMapping("/addPeriod")
    @ResponseBody
    public ResultJson addPeriod(Period period){
        periodService.addPeriod(period);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "添加成功", null);
    }

    /**
     * 更新 时期
     * @param period 时期data
     */
    @RequestMapping("/updPeriod")
    @ResponseBody
    public ResultJson updPeriod(Period period){
        periodService.updPeriod(period);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "更新成功", null);
    }

    /**
     * 跳转到 修改历史时期
     * @return
     */
    @RequestMapping("/toUpdPeriod")
    public String toUpdPeriod(ModelMap modelMap){
        List<Period> periodList = periodService.selectAllPeriodStartSort();
        modelMap.put("periodList", periodList);
        List<HistoryMain> historyMainList = historyMainService.selectAllAdSort();
        modelMap.put("historyMainList", historyMainList);

        return "updPeriod";
    }

    /**
     * 根据主键查询 时期
     * @param id 时期ID
     * @return
     */
    @RequestMapping("/selectPeriodById")
    @ResponseBody
    public ResultJson selectPeriodById(String id){
        Period period = periodService.selectById(id);
        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "查询成功", period);
    }


    /**
     * 根据主键删除 时期
     * @param id 时期ID
     */
    @RequestMapping("/delPeriod")
    @ResponseBody
    public ResultJson delPeriod(String id){
        periodService.delPeriod(id);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "删除成功", null);
    }


    /**
     * 跳转到 新增年号
     * @param modelMap
     * @return
     */
    @RequestMapping("/toAddReignTitle")
    public String toAddReignTitle(ModelMap modelMap){
//        List<HistoryMain> historyMainList = historyMainService.selectAllAdSort();
//        modelMap.put("historyMainList", historyMainList);
        modelMap.put("historyMainList", historyMainService.selectVoAllAdSort());

//        单个新增
//        return "addReignTitle";
        return "addBatchReignTitle";
    }


    /**
     * 新增 年号
     * @param reignTitle 年号data
     */
    @RequestMapping("/addReignTitle")
    @ResponseBody
    public ResultJson addReignTitle(ReignTitle reignTitle){
        reignTitleService.addReignTitle(reignTitle);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "添加成功", null);
    }

    /**
     * 检查 新增 年号 示例，参考
     * @param start 开始时间
     * @param ad 年号起始
     * @param end 结束时间
     * @param emperor  帝王
     * @param regin 年号
     * @return
     */
    @RequestMapping("/checkBatchReignTitleEffect")
    @ResponseBody
    public ResultJson checkBatchReignTitleEffect(String start, Integer ad, String end, String emperor, String regin){
        List<ReignTitle> titleList = buildReignTitle(start, ad, end, emperor, regin);

        // 返回数据
        Map<String, ReignTitleVo> map = new HashMap<>();
        if (titleList != null && titleList.size() > 0){
            // 构建返回结果
            ReignTitle startReign = titleList.get(0);
            ReignTitleVo startVo = new ReignTitleVo();
            startVo.setEmperor(startReign.getEmperor());
            startVo.setRegin(startReign.getRegin());
            startVo.setHistory(historyMainService.selectHistoryMainById(startReign.getHistoryId()).getAd());

            ReignTitle endReign = titleList.get(titleList.size() - 1);
            ReignTitleVo endVo = new ReignTitleVo();
            endVo.setEmperor(endReign.getEmperor());
            endVo.setHistory(historyMainService.selectHistoryMainById(endReign.getHistoryId()).getAd());
            endVo.setRegin(endReign.getRegin());

            map.put("startVo", startVo);
            map.put("endVo", endVo);
        }

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "请求成功", map);
    }

    /**
     * 批量 新增 年号
     * @param start 开始时间
     * @param ad 年号起始
     * @param end 结束时间
     * @param emperor  帝王
     * @param regin 年号
     * @return
     */
    @RequestMapping("/addBatchReignTitle")
    @ResponseBody
    public ResultJson addBatchReignTitle(String start, Integer ad, String end, String emperor, String regin){
        List<ReignTitle> titleList = buildReignTitle(start, ad, end, emperor, regin);

        reignTitleService.saveBatch(titleList);
        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "添加成功", null);
    }

    /**
     * 更新 年号
     * @param reignTitle 年号data
     */
    @RequestMapping("/updReignTitle")
    @ResponseBody
    public ResultJson updReignTitle(ReignTitle reignTitle){
        reignTitleService.updReignTitle(reignTitle);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "更新成功", null);
    }


    /**
     * 根据主键删除 年号
     * @param id 年号ID
     */
    @RequestMapping("/delReignTitle")
    @ResponseBody
    public ResultJson delReignTitle(String id){
        reignTitleService.delReignTitle(id);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "删除成功", null);
    }

    /**
     * 跳转到 更新年号
     * @param id 年号ID
     * @param modelMap
     * @return
     */
    @RequestMapping("/toUpdReignTitle")
    public String toUpdReignTitle(String id, ModelMap modelMap){
        ReignTitle reignTitle = reignTitleService.selectById(id);
        if (reignTitle != null){
            modelMap.put("reignTitle", reignTitle);
        }
        List<HistoryMain> historyMainList = historyMainService.selectAllAdSort();
        if (historyMainList != null && historyMainList.size() > 0){
            modelMap.put("historyMainList", historyMainList);
        }

        return "updReignTitle";
    }

    /**
     * 跳转到 新增地点映射
     * @return
     */
    @RequestMapping("/toAddLand")
    public String toAddLand(){
        return "addLand";
    }

    /**
     * 跳转到 地点查看界面
     * @param page 分页对象
     * @param modelMap
     * @param place 地名，搜索用
     * @return
     */
    @RequestMapping("/toLandList")
    public String toLandList(Page<Land> page, ModelMap modelMap, String place){
        Page<Land> landPage = landService.selectListByPlace(page, place);
        if (landPage != null){
            modelMap.put("landPage", landPage);
        }
        if (!CheckTool.checkNull(place)){
            modelMap.put("place", place);
        }

        return "landList";
    }


    /**
     * 新增 地点映射
     * @param land 地点映射data
     */
    @RequestMapping("/addLand")
    @ResponseBody
    public ResultJson addLand(Land land){
        landService.addLand(land);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "添加成功", null);
    }

    /**
     * 更新 地点映射
     * @param land 地点映射data
     */
    @RequestMapping("/updLand")
    @ResponseBody
    public ResultJson updLand(Land land){
        landService.updLand(land);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "更新成功", null);
    }


    /**
     * 根据主键删除 地点映射
     * @param id 地点映射id
     */
    @RequestMapping("/delLand")
    @ResponseBody
    public ResultJson delLand(String id){
        landService.delLand(id);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "删除成功", null);
    }

    /**
     * 跳转到地点更新
     * @param id 地点主键
     * @param modelMap
     * @return
     */
    @RequestMapping("/toUpdLand")
    public String toUpdLand(String id, ModelMap modelMap){
        Land land = landService.selectById(id);
        if (land != null){
            modelMap.put("land", land);
        }

        return "updLand";
    }


    /**
     * 新增 历史地图
     * @param historyImg 历史地图
     */
    @RequestMapping("/addHistoryImg")
    @ResponseBody
    public ResultJson addHistoryImg(HistoryImg historyImg, @RequestParam(value = "file", required = false) MultipartFile multipartFile){
        historyImgService.addHistoryImg(historyImg, multipartFile);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "添加成功", null);
    }

    /**
     * 更新 历史地图
     * @param historyImg 历史地图
     */
    @RequestMapping("/updHistoryImg")
    @ResponseBody
    public ResultJson updHistoryImg(HistoryImg historyImg, @RequestParam(value = "imgFile", required = false) MultipartFile multipartFile){
        historyImgService.updHistoryImg(historyImg, multipartFile);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "更新成功", null);
    }


    /**
     * 根据主键删除 历史地图
     * @param id 历史地图ID
     */
    @RequestMapping("/delHistoryImg")
    @ResponseBody
    public ResultJson delHistoryImg(String id){
        historyImgService.delHistoryImg(id);

        return new ResultJson(null, ResultEnum.SUCCESS.getStatus(), "删除成功", null);
    }

    /**
     * 跳转到 新增图片
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/toAddImg")
    public String toAddImg(String id, ModelMap modelMap){
        modelMap.put("id", id);
        List<HistoryImg> imgList =  historyImgService.selectByEventId(id);
        if (imgList != null && imgList.size() > 0){
            modelMap.put("imgList", imgList);
        }
        return "addImg";
    }

    /**
     * 读取硬盘图片回显工具类
     * @param id 图片id
     */
    @RequestMapping("/read")
    public void imgRead(HttpServletResponse response, String id){
        historyImgService.imgRead(response, id);
    }


    /**
     * 构建年号数据
     * @param start 开始时间
     * @param ad 年号起始
     * @param end 结束时间
     * @param emperor 帝王
     * @param regin 年号
     * @return
     */
    private List<ReignTitle> buildReignTitle(String start, Integer ad, String end, String emperor, String regin){
        if (CheckTool.checkNull(start)){
            throw new ServiceException("起始年份不能为空");
        }
        start = start.replaceAll(",", "");
        int startNum = Integer.parseInt(start);
        int endNum = 0;
        if (CheckTool.checkNull(end)){
            endNum = startNum;
        } else {
            end = end.replaceAll(",", "");
            endNum = Integer.parseInt(end);
        }
        if (startNum > endNum){
            throw new ServiceException("起始年份不能大于结束年份");
        }
        if (ad == null || ad < 1){
            throw new ServiceException("年号起始数必须大于0");
        }
        if (CheckTool.checkNull(emperor)){
            throw new ServiceException("帝王不能为空");
        }
        if (CheckTool.checkNull(regin)){
            throw new ServiceException("年号不能为空");
        }

        Timestamp timestamp = CommonTool.getTimestamp();
        //要构建的数量
        List<ReignTitle> titleList = new ArrayList<>();
        for (int i = startNum; i < endNum + 1; i ++){
            //查询历史主表
            HistoryMain historyMain = historyMainService.selectHistoryMainByAdNotThis(i, null);
            if (historyMain == null){
                //说明没有这个主干，直接忽略
                ad ++;
                continue;
            }
            ReignTitle reignTitle = new ReignTitle();
            reignTitle.setId(CommonTool.getUUId());
            String zw = NumberConventerTool.execute(ad);
            if ("不合法的数字".equals(zw)){
                ad ++;
                continue;
            }
            if ("一".equals(zw)){
                zw = "元";
            }
            String nh = regin + zw + "年";
            System.out.println("年份：" + i + "-->" + nh);
            reignTitle.setRegin(nh);
            reignTitle.setHistoryId(historyMain.getId());
            ReignTitle reignTitleSQL = reignTitleService.selectReignByReginNotThis(null, nh, historyMain.getId());
            if (reignTitleSQL != null){
                //已经存在
                ad ++;
                continue;
            }
            reignTitle.setEmperor(emperor);
            reignTitle.setCreateDate(timestamp);
            reignTitle.setUpdateDate(timestamp);

            titleList.add(reignTitle);
            ad ++;
        }

        return titleList;
    }


}
